<template>
  <div class="app-container">

   <div class="filter-container">
    
      <el-select v-model="selectValue"  placeholder="请选择" class='inp_search' @change='change'>
          <el-option
          v-for="item in optionsData"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select>

      <el-select v-if='showRoles' v-model="selectRoles"  placeholder="请选择" class='inp_search' >
          <el-option
          v-for="item in optionsRoles"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select>
      
      <el-input v-if='!showRoles'
          placeholder="输入查询"
          v-model="input_conten"
          clearable class='inp_search'>
      </el-input>
      
      
      <el-button  class="filter-item" type="primary" icon="el-icon-search"  @click="searchList">
        搜索
      </el-button>
      <el-button v-if="role == '4'"  class="filter-item" type="success" icon="el-icon-plus"  @click="addStock('add','ruleForm')">
        添加
      </el-button>
      <el-button  class="filter-item" type="primary" icon="el-icon-refresh"  @click="resList">
        重置
      </el-button>
    </div>
     
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.userId === null">--</span>
          <span v-else> {{scope.row.userId}} </span>
        </template>
      </el-table-column>

      <el-table-column label="角色" width="200" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.role === null">--</span>
           <span v-else-if="scope.row.role == 4">总部</span>
           <span v-else-if="scope.row.role == 3">门店</span>
           <span v-else-if="scope.row.role == 2">员工</span>
           <span v-else-if="scope.row.role == 1">普通用户</span>
        </template>
      </el-table-column>

       <el-table-column label="推广角色" width="200" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.staffSupiorName === null">--</span>
           <span v-else> {{scope.row.staffSupiorName}} </span>
        </template>
      </el-table-column>

      <el-table-column label="用户名" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.userName === null">--</span>
          <span v-else> {{scope.row.userName}} </span>
        </template>
      </el-table-column>

      <el-table-column  label="手机号" width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.phone === null">--</span>
          <span v-else> {{scope.row.phone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="上级用户手机号" width="200" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.superiorOnePhone === null">--</span>
          <span v-else> {{scope.row.superiorOnePhone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="上上级用户手机号" width="200" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.superiorTwoPhone === null">--</span>
           <span v-else> {{scope.row.superiorTwoPhone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="门店手机号" width="200" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.staffSupiorPhone === null">--</span>
           <span v-else> {{scope.row.staffSupiorPhone}} </span>
        </template>
      </el-table-column>

      <el-table-column label="累计订单数" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.totalOrder === null">--</span>
           <span v-else> {{scope.row.totalOrder}} </span>
        </template>
      </el-table-column>

       <el-table-column label="累计消费金额" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.totalCost === null">--</span>
           <span v-else> {{scope.row.totalCost}} </span>
        </template>
      </el-table-column>

      <el-table-column label="积分" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.integral === null">--</span>
           <span v-else> {{scope.row.integral}} </span>
        </template>
      </el-table-column>

      <el-table-column label="小程序openId" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.opneid === null">--</span>
           <span v-else> {{scope.row.opneid}} </span>
        </template>
      </el-table-column>

      <el-table-column label="推广链接url中的手机号" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.superiorOnePhone === null">--</span>
           <span v-else> {{scope.row.superiorOnePhone}} </span>
        </template>
      </el-table-column>

      <el-table-column v-if='show'  label="密码" min-width="120" align="center">
        <template slot-scope="scope">
           <span v-if="scope.row.password === null">--</span>
           <span v-else> {{scope.row.password}} </span>
        </template>
      </el-table-column>

     <el-table-column v-if="role == '4'"  fixed="right" label="操作" width="120" align="center">
           <template scope="scope">
              <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row,'ruleForm')">修改</el-button>
           </template>
      </el-table-column>
     
      <el-table-column align="center" prop="created_at" label="用户等级" width="120" >
        <template>
           <span v-if="userGrade === null">--</span>
           <span v-else> {{userGrade}} </span>
        </template>
      </el-table-column>
    </el-table>
   <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"  @pagination="fetchData"/>

   <!-- 添加 -->
   <div class='formPosition' v-if='dialogFormVisible'>
   <div class='titleForm'>
          <div class='left_titleForm'>{{titleName}}</div>
          <span class="icon iconfont right_titleForm" @click="resetForm('ruleForm')">&#xe72d;</span>
   </div>
   <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm " :visible.sync="dialogFormVisible">
          
          <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="userName">
                     <el-input v-model="ruleForm.userName"></el-input>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phone">
                  <el-input v-model="ruleForm.phone"></el-input>
                  </el-form-item>
                </el-col>
          </el-row>

          <el-row :gutter="20" v-if="titleName=='修改'">
                <el-col :span="12">
                   <el-form-item label="用户Id" prop="userId">
                    <el-input v-model="ruleForm.userId" readonly></el-input>
                    </el-form-item>
                </el-col>
                
                <el-col  :span="12">
                  <el-form-item label="积分" prop="integral">
                  <el-input v-model="ruleForm.integral"></el-input>
                  </el-form-item>
                </el-col>
          </el-row>

           <el-row :gutter="20" v-if="titleName=='修改'">
                <el-col :span="12">
                  <el-form-item label="上级手机号" prop="superiorOnePhone">
                  <el-input v-model="ruleForm.superiorOnePhone" readonly></el-input>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="上上级手机号" prop="superiorTwoPhone">
                  <el-input v-model="ruleForm.superiorTwoPhone" readonly></el-input>
                  </el-form-item>
                </el-col>
          </el-row>

          <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item v-if="titleName == '修改'" label="角色" prop="role">
                      <el-select v-model="addSelectRoles"  placeholder="请选择" class='select_roles'  @change="getRole(addSelectRoles,'ruleForm')">
                            <el-option
                            v-for="item in optionsRoles"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                      </el-select>
                  </el-form-item>

                  <el-form-item v-if="titleName == '添加'" label="角色" prop="role">
                      <el-select v-model="addSelectRoles"  placeholder="请选择" class='select_roles'  @change="getRole(addSelectRoles,'ruleForm')">
                            <el-option
                            v-for="item in optionsRolesAdd"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                      </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12" >
                  <el-form-item  class='formItemStyle' label="门店" >
                      <el-select v-model="ruleForm.addSelectStores"  placeholder="请选择" class='select_roles' @change="getStaff(ruleForm.addSelectStores)">
                            <el-option
                            v-for="item in optionsStores"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.phone">  
                            </el-option>
                      </el-select>
                  </el-form-item>
                </el-col>
          </el-row>

          <el-row :gutter="20">
                <el-col :span="12">
                 <!-- <el-form-item label="所属部门" prop="staffSupiorName">
                  <el-input v-model="ruleForm.staffSupiorName"></el-input>
                  </el-form-item> -->
                  <el-form-item label="所属部门手机号" >
                      <el-input v-model="ruleForm.staffSupiorPhone"></el-input>
                  </el-form-item> 
                </el-col>

                <el-col :span="12">
                  <el-form-item label="密码" prop="password">
                      <el-input v-model="ruleForm.password" type="password"></el-input>
                  </el-form-item>
                </el-col>
          </el-row>

          

          <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          </el-form-item>
     </el-form>
    </div>
  </div>
   
  
</template>

<script>
import { getUserList , searchByPhone ,searchByRole ,addUser ,updateUser ,searchByUserId ,getRoles} from '@/api/userManage'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      role:'',
      chiceRole:'',
      input_conten:'',
      showRoles:false,
      show:false,
      optionsData: [{
          value: 'userId',
          label: 'ID'
        },{
          value: 'roles',
          label: '角色'
        },{
          value: 'userPhone',
          label: '手机号'
        }],
      optionsRoles:[{
          value: '4',
          label: '总部'
        },{
          value: '3',
          label: '门店'
        },{
          value: '2',
          label: '员工'
        },{
          value: '1',
          label: '普通用户(客户)'
        }],
      optionsRolesAdd:[{
          value: '4',
          label: '总部'
        },{
          value: '3',
          label: '门店'
        },{
          value: '2',
          label: '员工'
        }],
      selectRoles:'',
      selectValue: '',
      addSelectRoles:'',
      optionsStores: [], 
      optionsstaff: [],
      list: null,
      listLoading: true,
      total: 10,
      userGrade:'',
      titleName:'',
      listQuery:{
          page: 1,
          limit: 10,
      },
      dialogFormVisible:false,
      ruleForm: {
          addSelectStores:'',
          userName: '',
          phone: '',
          password: '',
          role: '',
          openid: '',
          staffSupiorPhone: '',
          staffSupiorName: '',
          superiorOnePhone:'',
          superiorTwoPhone:'',
          integral:''
        },
        cleanForm:{
            addSelectStores:'',
            userName: '',
            phone: '',
            password: '',
            role: '',
            openid: '',
            staffSupiorPhone: '',
            staffSupiorName: '',
            superiorOnePhone:'',
            superiorTwoPhone:'',
            integral:''
        },
        rules: {
          userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          phone: [
            {required: true, message: '请输入手机号', trigger: 'blur' },
            {
            pattern: /^1[0-9]{10}$/,
            message: '手机号格式不对',
            trigger: 'blur'
          },
          ],
           password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
          ],
          staffSupiorPhone: [
            { required: true, message: '请输入所属部门手机号', trigger: 'blur' },
          ],
          staffSupiorName: [
            { required: true, message: '请输入所属部门', trigger: 'blur' },
          ],
        }
    }
  },
  created() {
    const userInfo = localStorage.getItem('userInfo');
    this.role = JSON.parse(userInfo).role;
    this.fetchData()
    this.selectValue = this.optionsData[0].label;
    this.selectValue ='userId';
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const paramsData = {curPage:this.listQuery.page,pageSize:this.listQuery.limit}
        getUserList(paramsData).then(res => {
           const datas = res.data.obj;
           this.list = datas;
           this.total = res.data.countNum;
           for(var i=0;i<datas.length;i++){//判断用户等级
               const cost = datas[i].totalCost;
               if(cost){
                    cost = Number(cost.split('.')[0]);
               }else{
                    this.userGrade='普通用户'
               }
               if(cost<500){
                   this.userGrade='普通用户'
               }else if((cost<1000)&&(cost>500)){
                   this.userGrade='VIP用户'
               }
           }
           this.listLoading = false
        })
    },
   submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
             this.listLoading = true
             this.handleModify(formName);
          } else {
            console.log('提交失败!');
            return false;
          }
        });
      },
    handleModify(formName){//修改 提交
             const paramsModify ={//修改参数
                  userId:this.ruleForm.userId,
                  userName:this.ruleForm.userName,
                  phone:this.ruleForm.phone,
                  role:this.addSelectRoles,
                  password:this.ruleForm.password,
                  superiorOnePhone:this.ruleForm.superiorOnePhone,
                  superiorTwoPhone:this.ruleForm.superiorTwoPhone,
                  staffSupiorPhone:this.ruleForm.staffSupiorPhone,
                  staffSupiorName:this.ruleForm.staffSupiorName,
                  integral:this.ruleForm.integral,
             }
             const paramsAdd = {//添加参数
                  userName:this.ruleForm.userName,
                  phone:this.ruleForm.phone,
                  password:this.ruleForm.password,
                  role:this.addSelectRoles,
                  openid:this.ruleForm.openid,
                  superiorOnePhone:this.ruleForm.superiorOnePhone,
                  staffSupiorPhone:this.rulrForm.addSelectStores,
                  staffSupiorName:this.ruleForm.staffSupiorName,
                  code:''
                  }
              if(this.titleName == '添加'){
                  const paramsData = paramsAdd
                  addUser(paramsData).then(res => {
                      if(res.code == 200){
                           this.$notify({
                              message: '添加成功',
                              type: 'success',
                              duration: 2000
                          })
                      }else{
                          this.$notify({
                              message: '添加失败',
                              type: 'error',
                              duration: 2000
                          })
                      }
                      this.fetchData()
                  })
              }else{//修改
                   const paramsData = paramsModify
                   updateUser(paramsData).then(res => {
                      //this.list = res.data;
                      if(res.code == 200){
                           this.$notify({
                              message: '修改成功',
                              type: 'success',
                              duration: 2000
                          })
                      }else{
                          this.$notify({
                              message: '修改失败',
                              type: 'error',
                              duration: 2000
                          })
                      }
                      this.fetchData()
                  })
              }
            this.listLoading = false;
            this.dialogFormVisible = false; 
            this.resetForm(formName) 
      },
    resetForm(formName) {
        this.ruleForm = this.cleanForm;
        this.$forceUpdate();
        this.dialogFormVisible = false;  
    },
    addStock(formName){//处理弹出框添加和修改的状态
          this.dialogFormVisible = true; 
          this.titleName = '添加'
          this.ruleForm = this.cleanForm;
          this.addSelectRoles = '';//角色赋值 
          this.ruleForm.addSelectStores = '';
          this.ruleForm.password = '';
          this.ruleForm.staffSupiorPhone = '';
          this.$forceUpdate();
      },
    handleEdit(index, row ,formName) {//修改
          this.titleName = '修改'
          this.dialogFormVisible = true;
          this.ruleForm = Object.assign({}, row);
          this.addSelectRoles = row.role;//角色赋值
          this.ruleForm.addSelectStores = '';
          this.ruleForm.addSelectStores = row.staffSupiorName;
          this.ruleForm.password = row.password;
      },
    getRole(para,formName){//获取角色/门店
        this.ruleForm.addSelectStores = '';
        if(para == 4){
           para = 1;
        }else{
           para = '';
        }
        const paramsData = {type:para}
          getRoles(paramsData).then(res => {
                    const datas = res.data;
                    this.optionsStores = datas;
                })
      },
    getStaff(para){//获取员工
          var obj = {};
          obj = this.optionsStores.find(item =>{
              return item.phone === para 
          });
          this.ruleForm.staffSupiorPhone = obj.phone;
          this.ruleForm.staffSupiorName = obj.userName;
      },
    change(){
           if(this.selectValue == 'roles'){
              this.showRoles = true
           }else{
              this.showRoles = false
           }
           this.input_conten = '';
           this.selectRoles = '';
           this.$forceUpdate();
    },
    resList(){
      const userInfo = localStorage.getItem('userInfo');
      this.role = JSON.parse(userInfo).role;
      this.fetchData()
      this.selectValue = this.optionsData[0].label;
      this.selectValue ='userId';
    },
    searchList(){//搜索
         if((!this.input_conten)&&(!this.selectRoles)){
            this.fetchData();
            return false;
         }else{
            if(this.selectValue == 'userPhone'){//手机
                const paramsData = {phone:this.input_conten}
                 searchByPhone(paramsData).then(res => {
                    this.list = res.data.obj;
                })
            }else if(this.selectValue == 'roles'){
                 const paramsData = {role:this.selectRoles,curPage:this.listQuery.page,pageSize:this.listQuery.limit}
                 searchByRole(paramsData).then(res => {
                    this.list = res.data.obj;
                })
               
            }else{
               const paramsData = {userId:this.input_conten}
                 searchByUserId(paramsData).then(res => {
                    this.list = res.data.obj;
                })
                
            }
         }

      }
    }
  
 }
</script>
<style lang="scss">
 .filter-container{
   margin-bottom:20px;
 }
 .el-date-range-picker{
   margin-left:220px;
 }
 .inp_search{
   width:20%;
   margin-right:1%;        
 }
 .formPosition{
    width:70%;
    height:auto;
    background:#fff;
    position:absolute;
    left:15%;
    top:5%;
    z-index:999;
    padding:30px;
    box-shadow: 0px 0px 5px 5px #eee;
    border-radius: 5px;
 }
 .demo-ruleForm{
      width:95%;     
 }
 .titleForm{
     width:100%;
     height:30px;
     line-height:30px;
     margin-bottom:20px;
     font-size:1.1em;
     font-weight: 500;
 }
 .left_titleForm{
    float:left;
 }
 .right_titleForm{
    display:block;
    float:right;
 }
 .select_roles{
    width:100%;
 }
</style>
